
//
//  ActivityCenterViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/28.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyActivityViewController.h"
#import "ActivityCenterTableViewCell.h"
#import "ActivityDetailViewController.h"
static NSString * cellIndentifier = @"ActivityCenterTableViewCell";

@interface MyActivityViewController()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIView *selectedBackView;
@property (strong, nonatomic) IBOutlet UIView *selectedView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIButton *doingButton;
@property (strong, nonatomic) IBOutlet UIButton * doneButton;
@property(nonatomic,assign)BOOL doneActivity;
@property(nonatomic,strong)NSMutableArray * activitiesArray;
@end

@implementation MyActivityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _doneActivity = NO;
    _pageNO =  1;
    _activitiesArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.selectedBackView];
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];

}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
- (IBAction)goHome:(id)sender {
    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"ifLogin"];
    [self.navigationController  popViewControllerAnimated:YES];
}



#pragma mark == 切换活动
- (IBAction)exchangeActivity:(UIButton *)sender {
    if (sender == _doingButton) {
        _doingButton.selected = YES;
        _doneButton.selected = NO;
        [UIView animateWithDuration:0.2 animations:^{
            _selectedView.frame = flexibleFrame(CGRectMake(0, 41, 160, 1), YES);
        }];
        _doneActivity = NO;
    }else{
        _doingButton.selected = NO;
        _doneButton.selected = YES;
        [UIView animateWithDuration:0.2 animations:^{
            _selectedView.frame = flexibleFrame(CGRectMake(160, 41, 160, 1), YES);
        }];
        _doneActivity = YES;
    }
    [self addRefreshing];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIndentsList];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.activitiesArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIndentsList];
        });
    }
    
}
- (void)getIndentsList{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    if (_doneActivity == YES) {
         [dic setObject:@"3" forKey:@"mactState"];
    }else{
     [dic setObject:@"2" forKey:@"mactState"];
    }
   
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppactivity withHttpType:@"POST" withTag:SX_SX_queryAppactivity];
    
    
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 210*VerticalRatio();
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return _activitiesArray.count;
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ActivityCenterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell= [[ActivityCenterTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    
        NSString * image = _activitiesArray[indexPath.row][@"imgUrl"];
        if (image.length>0) {
            [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }else{
            cell.goodsImage.image =[UIImage imageNamed:@"photos1"];
        }
        cell.noticeTitle.text = [NSString stringWithFormat:@"%@",_activitiesArray[indexPath.row][@"title"]];
        cell.infoLabel.frame = flexibleFrame(CGRectMake(8, 22, 266, 20), YES);
        cell.infoLabel.numberOfLines = 0;
        cell.infoLabel.text  = [NSString stringWithFormat:@"%@",_activitiesArray[indexPath.row][@"subTitle"]];
        [cell.infoLabel sizeToFit];
    
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[_activitiesArray[indexPath.row][@"beginTime"] integerValue]/1000];
        NSDate *confromTimesp1 = [NSDate dateWithTimeIntervalSince1970:[_activitiesArray[indexPath.row][@"endTime"] integerValue]/1000];
        [formatter setDateFormat:@"yyyy年MM月dd"];
        NSString *beginTime = [formatter stringFromDate:confromTimesp];
        NSString *endTime = [formatter stringFromDate:confromTimesp1];
        cell.timeLabel.text = [NSString stringWithFormat:@"%@ - %@",beginTime,endTime];
    if (_doneActivity == YES) {
        cell.activityDoneButton.hidden = NO;
    }else{
        cell.activityDoneButton.hidden = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ActivityDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ActivityDetail"];
    page.objectId = _activitiesArray[indexPath.row][@"activityId"];
    [self.navigationController  pushViewController:page animated:YES];
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
   
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==SX_SX_queryAppactivity){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.activitiesArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.activitiesArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
            
            
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [self dismissWaitDialog];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
